package api

import (
	"fmt"
	"net/http"
	"os"
	"time"

	"gitee.com/h2ob/base"
	"gitee.com/h2ob/infra"
	"github.com/gin-gonic/gin"
)

func ossAvator(c *gin.Context) {
	name := c.Query("q")
	if name == "" {
		c.Status(http.StatusBadRequest)
		return
	}
	file := fmt.Sprintf("../upload/avator/%s", name)
	base.GLogger.Infof("file: %s", file)
	c.File(file)
}

func ossDownload(c *gin.Context) {
	name := c.Query("q")
	tag := c.Query("tag")
	if name == "" || tag == "" {
		c.Status(http.StatusBadRequest)
		return
	}
	var r = []rune(name)
	file := fmt.Sprintf("../upload/%s/%s/%s", tag, string(r[0:6]), string(r[6:]))
	base.GLogger.Infof("file: %s", file)
	c.File(file)
}

func ossUpload(c *gin.Context) {
	tag := c.Query("tag")
	if tag == "" {
		c.Status(http.StatusBadRequest)
		return
	}
	file, err := c.FormFile("file")
	if err != nil {
		base.GLogger.Info("Can not find file")
		c.String(http.StatusBadRequest, "Can not find file")
		return
	}
	yyyyMM := base.GetYYMM(time.Now())
	dir := fmt.Sprintf("../upload/%s/%s", tag, yyyyMM)
	os.MkdirAll(dir, 0766)
	uuid := base.GetUuid()
	ftype := infra.GetFileType(file.Filename)
	err = c.SaveUploadedFile(file, fmt.Sprintf("%s/%s%s", dir, uuid, ftype))
	if err != nil {
		c.Status(http.StatusInsufficientStorage)
		return
	}
	c.String(http.StatusOK, fmt.Sprintf("%s%s%s", yyyyMM, uuid, ftype))
}
